package com.scr1pt.extension.model.date

import com.scr1pt.extension.addDays
import com.scr1pt.extension.dateTime
import java.util.*

/**
 * 说明: 日期范围，单位：天，闭区间
 *
 * 创建者: tum0r
 *
 * 时间: 2021/10/16 20:43
 *
 * @param[start] 起始时间，包含
 * @param[endInclusive] 结束时间，包含
 * @param[step] 间隔
 */
data class DateRange(override val start: Date, override val endInclusive: Date, private val step: Int) : Iterable<Date>, ClosedRange<Date> {
    override fun iterator(): Iterator<Date> = DateIterator(start, endInclusive, step)
    infix fun step(step: Int): DateRange = DateRange(start, endInclusive, this.step * if (step == 0) 1 else if (step > 0) step else step)
}

/**
 * 说明: 日期范围迭代器，单位：天
 *
 * 创建者: tum0r
 *
 * 时间: 2021/10/16 20:43
 *
 * @param[first] 起始时间，包含
 * @param[last] 结束时间，包含
 * @param[step] 间隔
 */
class DateIterator(first: Date, last: Date, private val step: Int) : Iterator<Date> {
    private val firstDate = first.dateTime()
    private val lastDate = last.dateTime()
    private var hasNext = if (step > 0) firstDate <= lastDate else firstDate >= lastDate
    private var next = if (hasNext) firstDate else lastDate
    override fun hasNext(): Boolean = hasNext
    override fun next(): Date {
        if (!hasNext) throw Exception("No next")
        val result = next
        next = next.addDays(step)
        hasNext = if (step > 0) next <= lastDate else next >= lastDate
        return result
    }
}